package servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.MonthStatistics;
import bean.MonthStatisticsListBean;
import factory.DaoFactory;

/**
 * Servlet implementation class MonthSaleStatisticsServlet
 */
@WebServlet("/MonthSaleStatisticsServlet")
public class MonthSaleStatisticsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MonthSaleStatisticsServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		List<MonthStatistics> list = DaoFactory.getRecordDao().findAllByMonth();
		MonthStatisticsListBean monthList = new MonthStatisticsListBean(list);
		request.setAttribute("monthList", monthList);
		
		float avgX = 0;
		float avgY = 0;
		float xy = 0;
		float sqrX = 0;
		int i = 1;
		for (i = 1; i <= list.size(); i++) {
			float y = list.get(i - 1).getTotalConsumption();
			avgX += i;
			avgY += y;
			xy += i * y;
			sqrX += i * i;
		}
		avgX = avgX / list.size();
		avgY = avgY / list.size();
		float b = (xy - list.size() * avgX * avgY) / (sqrX - list.size() * avgX * avgX);
		float a = avgY - b * avgX;
		List<MonthStatistics> list2 = new ArrayList<MonthStatistics>();
		for (i = 0; i < list.size(); i++) {
			list2.add(new MonthStatistics(list.get(i).getMonth(), a + b * (i + 1)));
		}
		MonthStatisticsListBean line = new MonthStatisticsListBean(list2);
		request.setAttribute("line", line);
		
		String address ="/jsp/MonthSaleStatistics.jsp";
		if (b < 0) {
			address += "?exception=true";
		}
		
		RequestDispatcher dispatcher =request.getRequestDispatcher(address);
		dispatcher.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
